﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using Autofac.Extensions.DependencyInjection;
using AutoMapper;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Swashbuckle.AspNetCore.Swagger;
using Swashbuckle.AspNetCore.SwaggerUI;
using Xierun.IServices;
using Xierun.Services;
using Xierun.WebApi.Extensions;
using Xierun.WebApi.Loggers;

namespace Xierun.WebApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public static readonly LoggerFactory EFLoggerFactory = new LoggerFactory(new[] { new EFLoggerProvider() });

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<EntityContext>(options =>
            {
                options.UseSqlServer(
                    Configuration.GetConnectionString("MssqlConnection")).UseLoggerFactory(EFLoggerFactory);
                //options.UseInMemoryDatabase(Configuration.GetConnectionString("MssqlConnection"));
            });

            services.AddScoped<IBase_UserService, Base_UserService>();


            services.AddAutoMapper(Assembly.GetExecutingAssembly());

            services.AddSwaggerGen(option =>
            {
                option.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
                {
                    Version = "v1",
                    Title = " Xierun.WebApi",
                    Description = "by 小谢"
                });

                var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
                option.IncludeXmlComments(xmlPath);

                //option.OperationFilter<GlobalHttpHeaderOperationFilter>(); // 添加httpHeader参数
                //if (!string.IsNullOrEmpty(identityServer))
                //{
                //    //接入identityserver
                //    option.AddSecurityDefinition("oauth2", new OAuth2Scheme
                //    {
                //        Flow = "implicit", // 只需通过浏览器获取令牌（适用于swagger）
                //        AuthorizationUrl = $"{identityServer}/connect/authorize",//获取登录授权接口
                //        Scopes = new Dictionary<string, string> {
                //            { "openauthapi", "同意openauth.webapi 的访问权限" }//指定客户端请求的api作用域。 如果为空，则客户端无法访问
                //        }
                //    });
                //    option.OperationFilter<AuthResponsesOperationFilter>();
                //}

            });


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
            
            return new AutofacServiceProvider(AutofacExt.InitAutofac(services));
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseExceptionJsonHandler();

            app.UseSwagger();
            
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "V1 Docs");
                c.DocExpansion(DocExpansion.None);
                c.OAuthClientId("Xierun.WebApi");  //oauth客户端名称
                c.OAuthAppName("Xierun.WebApi"); // 描述
            });

            app.UseMvc();
        }
    }
}
